//var hurl = "http://md.rovine.cn";	//域名 
var hurl = "http://app.soft101.com";	//域名
var version = '7.09';				//安卓版本
//var version = '1.1';				//ios版本
/*
 * 封装的ajax 
 * 使用方法：
 * let data= {
 * 		url:"路径",
 * 		data:{
 * 			参数:值,.......
 * 
 * 		}
 * }
 * ajax(data,function(res){
 * 		console.log(res);
 * })
 */
function ajax(data, func,type,ferr) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type:type||"post",
		url: hurl + data.url,
		dataType: "json",
		data: data.data||"",
		error: function(err) {
			console.log("err",err);
			console.log("失败:" + JSON.stringify(err));
			mui.toast("网络出错，请检查网络连接！");
			if(ferr){
				ferr(err)
			}
		},
		success: function(data) {
			if(data.error_code > 0) {
				//console.log(data);
				console.log( JSON.stringify(data));
				if(ferr){
					ferr(data)
				}
				if(data.msg == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.msg);
				}
			}
			if(data.error_code == 0) {
				if(func){
					func(data);
				}
			}
		},
		complete: function() {
			mui.hideLoading();
		}
	});
}

/*
 数组去重
 * */
function remove_duplicate(array){
		var r = [];
		for(var i = 0, l = array.length; i < l; i++) {
			for(var j = i + 1; j < l; j++){
				if(array[i].id === array[j].id) {
					j = ++i;
				}
			}
			r.push(array[i]);
		}
		return r;
}

/*
 数组去重
 * */
function remove_duplicate_document(array){
		var r = [];
		for(var i = 0, l = array.length; i < l; i++) {
			for(var j = i + 1; j < l; j++){
				if(array[i].order_number == array[j].order_number) {
					j = ++i;
				}
			}
			r.push(array[i]);
		}
		return r;
}
function ajaxasync(data, func,type) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type:type||"post",
		url: hurl + data.url,
		dataType: "json",
		data: data.data||"",
		async : false,
		error: function(err) {
			console.log("失败:" + JSON.stringify(err));
			mui.toast("网络出错，请检查网络连接！");
			
		},
		success: function(data) {
			if(data.error_code > 0) {
				//console.log(data);
				console.log( JSON.stringify(data));
				if(data.msg == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.msg);
				}
			}
			if(data.error_code == 0) {
				if(func){
					func(data);
				}
			}
		},
		complete: function() {
			mui.hideLoading();
		}
	});
}
/*
 * 关闭页面
 */
function closewin(){
    if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") !=-1) {
        window.location.href="about:blank";
        window.close();
    } else {
        window.opener = null;
        window.open("", "_self");
        window.close();
       
    }
    //openlogin();
}



/*
 * 判断是移动还是pc
 */
function gomatch() {
                if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                    /*window.location.href="你的手机版地址";*/
                    return "mobile";
                }
                else {
                    /*window.location.href="你的电脑版地址";    */
                    return "pc";
                }
                
            }
/*
 * 判断是什么系统
 */
function getxitong() {
    var u = navigator.userAgent, app = navigator.appVersion;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isAndroid) {
       //这个是安卓操作系统
       return "android";
    }
    if (isIOS) {
　　　　//这个是ios操作系统
	   return "ios";
    }
}

/*
 * 判断是什么系统
 */
function is_ios() {
    var u = navigator.userAgent, app = navigator.appVersion;
    //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    /*if (isAndroid) {
       //这个是安卓操作系统
       return "android";
    }*/
    if (isIOS) {
　　　　//这个是ios操作系统
	   return true;
    }else{
    	return false;
    }
}

/*
 * 获取id对象
 */
function g(id){
	return document.getElementById(id);
}

/*
 * 封装的用于上传base64格式的文件
 * 用法和上面一样
 */
function ajaxbase64(data, func) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type: "POST",
		url: hurl + data.url,
		dataType: "json",
		data: data.data,
		error: function(err) {
			//console.log("失败:" + err);
			console.log("失败:" + JSON.stringify(err));
			mui.toast("图片上传失败，请重新上传");
		},
		success: function(data) {
			if(data.code == -1) {
				if(data.message == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.message);
				}
			}
			if(data.code == 1) {
				func(data);
			}
		},
		complete: function() {
			mui.hideLoading();
		}
	});
}
/*
 * 获取acctoken的函数，直接可以调用方法获取token
 */
function acctoken() {
	var access_token = null
	try {
		var value = localStorage.getItem('accesstoken') || "";
		if(value) {
			access_token = value
		}
	} catch(e) {}
	return access_token;

}
/*
 * base64的字符串转成blob
 */

function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for(var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {
		type: mimeString
	});
}
/*
 * 查看图片是否存在
 */
function ishasimg(pathImg) {
	var ImgObj = new Image();
	ImgObj.src = pathImg;
	//console.log(ImgObj);
	if(ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
		return true;
	} else {
		return false;
	}
}

/*
 * 获取路径？后面的参数
 */
function getrequest() {
	var url = location.search; //获取url中"?"符后的字串  
	var theRequest = new Object();
	if(url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		for(var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = unescape(decodeURI(strs[i].split("=")[1]));
		}
	}
	return theRequest;
}
function getBase64Image(imgurl, fun) {
	//mui.toast("开始压缩图片");
	mui.showLoading("正在压缩");
	var img = new Image();
	img.src = imgurl;
	var div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		var canvas = document.createElement("canvas");
		var imgw = img.width / 1.5;
		var imgh = img.height / 1.5;
		canvas.width = imgw;
		canvas.height = imgh;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, imgw, imgh);
		var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		var dataURL = canvas.toDataURL("image/" + ext);
		console.log(dataURL);
		if(dataURL.length > 1048576){
			getBase64Image(dataURL,fun);
		}else{
			mui.hideLoading();
			var lsit = {
				dataURL: dataURL,
				type: "image/" + ext
			}
			fun(lsit);
		}
	}
}


//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
	var arr = dataurl.split(',');
	console.log(arr);
	var mime = arr[0].match(/:(.*?);/)[1];
	console.log(mime);
	var bstr = atob(arr[1]);
	console.log(bstr);
	var n = bstr.length;
	var u8arr = new Uint8Array(n);
	while(n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	console.log(u8arr);
	return new File([u8arr], filename, {
		type: mime
	});
}

/*
 * base64转blob
 */
function b64toBlob(b64Data, contentType, sliceSize) {
	contentType = contentType || '';
	sliceSize = sliceSize || 512;
	var byteCharacters = atob(b64Data.substring(b64Data.indexOf(',') + 1));
	var byteArrays = [];
	for(var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		var slice = byteCharacters.slice(offset, offset + sliceSize);
		var byteNumbers = new Array(slice.length);
		for(var i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}
		var byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}
	var blob = new Blob(byteArrays, {
		type: contentType
	});
	return blob;
}



//验证非法字符
 function checkStr(strTest) {
     var pat = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i");
     var strArr = strTest.split("");
     for (var i = 0; i < strArr.length; i++) {
         var str = strTest.charAt(i);
         if (pat.test(strArr[i]) == true) {
             strArr[i] = "()";
             console.log("含有非法字符");
             return false
         }
     }
     return true
 }  
 
 //手机号验证
function phone_validation(phone) {
	if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
		mui.toast("手机号码有误，请重新输入");
		return false;
	} else {
		return true;
	}
}



//返回上一页刷新
/*
 * 只要在父页面 有onshow() 这个函数,就可以实现返回刷新
 */
function muiback_show(){
	var mtype = gomatch();
	console.log(mtype)
	if(mtype != "mobile"){
		mui.back();
	}else{
		console.log(2)
	    //获取父页面对象
	    try{
	    	var aPage = plus.webview.currentWebview().opener();
	    //执行父页面函数
	    	aPage.evalJS('onshow()');
	    }catch(e){
	    	//TODO handle the exception
	    }
	    //关闭
	   mui.back();
		
	}
}



//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}


//四舍五入
function round(num){
	return Math.round(num)
}

//返回上一页刷新
function back_show(){
	setTimeout(function(){
		try{
	    	var aPage = plus.webview.currentWebview();
	    	var bPage = aPage.opener();
	    	//执行父页面函数
	    	bPage.evalJS('onshow()');
	    	mui.back();
	    }catch(e){
	    	//TODO handle the exception
	    	mui.back();
	    }
	},300)
	
}

//返回上一页刷新
function back_show_num(){
	setTimeout(function(){
		try{
	    	var aPage = plus.webview.currentWebview();
	    	var bPage = aPage.opener();
	    	var cPage = bPage.opener();
	    	//执行父页面函数
	    	aPage.close();
	    	bPage.close();
			//mui.back();
	    	cPage.evalJS('onshow()');
	    }catch(e){
	    	//TODO handle the exception
	    	mui.back();
	    }
		
	},300)
	
}


/*
 * 获取当天时间
 */
function get_time(){
	var date = new Date();
	var Y = date.getFullYear();	/*年*/
	var M = date.getMonth() + 1;/*月*/
	var D = date.getDate();		/*日*/
	var h = date.getHours();	/*时*/
	var m = date.getMinutes();	/*分*/
	var s = date.getSeconds();	/*秒*/
	return {Y:Y,M:M,D:D,h:h,m:m,s:s}
}

/*
 * 时间比
 * t1比t2 早就是true 否则是false
 */
function time_than_size(t1,t2){
	var tlist1 = t1.split(":"),
		tlist2 = t2.split(":");
	var flag = true;
	var i = 0;
	while(i < tlist1.length){
		if(parseInt(tlist1[i]) > parseInt(tlist2[i])){
			flag = false;
			break;
		}else{
			i++;
		}
	}
	return flag;
}

function upToRefresh(){
	mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
	mui('#refreshContainer').pullRefresh().refresh(true);
}

function back_toast(str){
	setTimeout(function(){
		try{
	    	var aPage = plus.webview.currentWebview();
	    	var bPage = aPage.opener();
	    	//执行父页面函数
	    	bPage.evalJS('ontoast('+str+')');
	    	mui.back();
	    }catch(e){
	    	//TODO handle the exception
	    	mui.back();
	    }
	},300)
}

 
mui.plusReady(function() {
	//判断是否支持沉浸式 
	var isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
	if(isImmersedStatusbar){
		//获取状态栏高度 
		var StatusbarHeight = plus.navigator.getStatusbarHeight();
		//获取元素计算后的高度 
		var heightH = document.getElementsByClassName('mui-bar-nav')[0].offsetHeight;
		//设置导航栏高度为原高度+状态栏高度+设置内边距高度为状态栏高度
		document.getElementsByClassName('mui-bar-nav')[0].style.height=heightH+StatusbarHeight+'px';
		document.getElementsByClassName('mui-bar-nav')[0].style.paddingTop=StatusbarHeight+'px';
		//设置content 样式内上边距增加状态栏高度 
		document.getElementsByClassName('mui-content')[0].style.paddingTop = heightH + StatusbarHeight + 'px';
	}
	/*
	 * 解决ios 第二次input不能获取焦点问题
	 */
	if(!is_ios()){
		var inputs =  document.getElementsByTagName("input");
		if(inputs.length){
			for(var inputindex = 0; inputindex < inputs.length; inputindex++){
				(function(index){
					inputs[index].addEventListener("click",function(){
						this.focus();
					})
				})(inputindex)
			}
		}
	}
})